package com.lkl.hystrixdemo.order.utils;

import com.lkl.hystrixdemo.order.service.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class RedisTokenUtils {

    @Autowired
    RedisService redisService;

    private static final long expiredTime = 60 * 60; //一个小时

    /**
     * 生成token并存入redis
     * @return
     */
    public String getToken() {
        String token =  UUID.randomUUID().toString().replaceAll("\\-", "");
        redisService.set(token, token, expiredTime);
        return token;
    }

    /**
     * 验证token的有效性
     * @param token
     * @return
     */
    public boolean isTokenValid(String token) {
        if (StringUtils.isEmpty(token)) {
            System.out.println("令牌为空，非法请求");
            return false;
        }

        Object value = redisService.getKey(token);


        if (value == null || StringUtils.isEmpty(value + "")) {
            System.out.println("重复提交");
            return false;
        }
        System.out.println("value:" + value);

        if (redisService.remove(token)) {
            System.out.println("令牌验证成功");
            return true;
        }
        return false;
    }

}
